package com.zmn.oms.task.job.third.jdhuadi;

import com.github.ltsopensource.core.domain.Action;
import com.github.ltsopensource.core.domain.Job;
import com.github.ltsopensource.spring.tasktracker.JobRunnerItem;
import com.github.ltsopensource.spring.tasktracker.LTS;
import com.github.ltsopensource.tasktracker.Result;
import com.zmn.common.dto.ResultDTO;
import com.zmn.manager.lts.interfaces.task.TaskManager;
import com.zmn.oms.manager.utils.TaskConsts;
import com.zmn.oms.third.jd_huadi.JdHuadiConsts;
import com.zmn.oms.third.jd_huadi.service.JdHuadiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * 类描述：京东华帝渠道刷新access token有效期的任务，1小时执行一次
 *
 * @author xiewenbing
 * @date 2020/05/21 11:12
 */
@LTS
@Slf4j
public class JdHuaDiRefreshTokenJob {
    @Autowired
    JdHuadiService jdHuadiService;

    @Resource
    TaskManager taskManager;

    /**
     * 每隔60分钟，刷新access token
     */
    @PostConstruct
    void init() {

        // 提交定时任务
        Job job = new Job();
        job.setTaskId(TaskConsts.TASK_ID_JDHUADI_REFRESH_ACCESS_TOKEN);
        job.setParam(TaskManager.SHARD_FIELD, TaskConsts.TASK_ID_JDHUADI_REFRESH_ACCESS_TOKEN);
        job.setCronExpression("0 0 /1 * * ?");
        job.setReplaceOnExist(true);
        ResultDTO result = taskManager.submitTask(job);
        if (!result.getStatusBool()) {
            log.error("#oms#jdhuadi_refreshAccessToken# job submit fail...");
        }
    }

    /**
     * 拉取京东华帝渠道的access token
     * @param job
     * @return
     */
    @JobRunnerItem(shardValue = TaskConsts.TASK_ID_JDHUADI_REFRESH_ACCESS_TOKEN)
    public Result runWorkJob(Job job) {

        if (!JdHuadiConsts.POWER_ON) {
            log.info("【{}】<refresh access token> 该功能没有开启。", JdHuadiConsts.CHANNEL_NAME);
            return new Result(Action.EXECUTE_FAILED, "不需要执行!");
        }

        jdHuadiService.refreshAccessToken();
        log.info("#oms#jdhuadi_refreshAccessToken#刷新access token");
        return new Result(Action.EXECUTE_SUCCESS, "执行成功了!");
    }
}
